<?php
namespace App\Adshopuser\Models;
use Common\BaseModel;
class BShopGoodsSku extends BaseModel
{
    public $res;
    public $expire;

    public function initialize()
    {
        parent::initialize();
        $this->setSource('b_shop_goods_sku');
    }

    public function get_list($params=[]){
        $page = intval($params['page']);
        $size = intval($params['limit']);
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $condtions="g.shop_id={$params['shop_id']}";
        if(isset($params['stock']) && !empty($params['stock'])){
            $condtions .= " AND (g.stock<{$params['stock']} OR sku.stock<{$params['stock']})";
        }
        $sql="
        SELECT g.id,sku.id as sku_id,g.goods_sn,g.name,g.stock,sku.stock as sku_stock,g.status,g.shop_id,sku.value_ids,g.created_at FROM `b_shop_goods` as g
left join b_shop_goods_sku as sku on sku.goods_id = g.id
where $condtions
limit $page,$size";
        $items = $this->getDI()->get('dbMaster')->fetchAll($sql);

        $BShopGoodsSkuDb = new BShopSkuValue();
        foreach($items as $key=>$value){
            if($value['value_ids']){
                $value_ids = str_replace("_",",",$value['value_ids']);
                $get_sku_items = $BShopGoodsSkuDb->find(array(
                    'conditions'=>"id in($value_ids)",
                    'columns'=>'value_name'
                ))->toarray();
                $items[$key]['sku_value_name'] = array_column($get_sku_items,'value_name') ? implode('-',array_column($get_sku_items,'value_name')):'';
            }else{
                $items[$key]['sku_value_name'] = "";
            }
        }
        $get_list['items'] = $items;



        $count_sql="
        SELECT count(g.id) as count FROM `b_shop_goods` as g
left join b_shop_goods_sku as sku on sku.goods_id = g.id
where $condtions";
        $g_count = $this->getDI()->get('dbMaster')->fetchOne($count_sql);
        $get_list['total'] = isset($g_count['count']) && !empty($g_count['count']) ? (int)$g_count['count'] : 0;
        return $get_list;
    }

}
